/**
 * 格式化雷达图
 * @des {
 *   仅格式化组件所需要的数据
 * }
 */
import { $each, $isEmptyArr, isNullOrEmpty } from '../index';
import { handleConditionExtend } from '../conditionFormat/useConditionFormat.js';
/**
 * 格式化X轴
 * @param {object} datasets
 */
export function processXAis(datasets) {
  const { dimensions, source, fieldNameChainMap, conditionData } = datasets;
  const xData = [];
  const xMap = {};
  const conditionXMap = {};
  const { xAxis, legend } = dimensions;
  // 判断是否是多维度
  let xAxisArr = [];
  if (xAxis.includes('&')) {
    xAxisArr = xAxis.split('&');
  } else {
    xAxisArr = [xAxis];
  }
  source.forEach((item) => {
    let XAXIS = '';
    // 联动使用
    const values = [];
    if (xAxisArr.length) {
      xAxisArr.forEach((xAxisItem) => {
        XAXIS += item[xAxisItem];
        values.push(item[xAxisItem]);
        // 如果颜色维度存在,维度数据需要去重
        if(legend) {
          // 根据原始字段名称收集数据 维度数据存在相同的数据需要去重
          if (fieldNameChainMap?.xAxis[xAxisItem] && !conditionXMap[item[xAxisItem]]) {
            conditionData[fieldNameChainMap?.xAxis[xAxisItem]].push({ value: item[xAxisItem] });
            conditionXMap[item[xAxisItem]] = true;
          }
        } else {
          if (fieldNameChainMap?.xAxis[xAxisItem]) {
            conditionData[fieldNameChainMap?.xAxis[xAxisItem]].push({ value: item[xAxisItem] });
          }
        }
      });
    }
    // 去重
    if (!xMap[XAXIS]) {
      xData.push({
        value: XAXIS,
        values,
      });
      xMap[XAXIS] = true;
    }
  });
  return xData;
}

/**
 * 格式化series
 * @param {object} datasets
 * @param {Array} xData x轴数据
 */
export function processSeriesData(datasets, options) {
  let seriesData = [];
  const { dimensions, source, type, fieldNameChainMap, conditionData, conditionOptions } = datasets;
  const { xData, chartType='radar' } = options;
  // 如果是静态数据
  if (type === 'STATIC') {
    return radarStaticFormat(source, chartType).resultMap;
  }
  const { yAxis, legend: legendKey, xAxis, yAxisCondition } = dimensions;
  let yAxisArr = [];
  let xAxisArr = [];
  let yAxisConditionArr = [];//用来单独存储条件项名称
  // 判断是否是多维度
  if (xAxis.includes('&')) {
    xAxisArr = xAxis.split('&');
  } else {
    xAxisArr = [xAxis];
  }
  // 判断是否是多度量
  if (yAxis.includes('&')) {
    yAxisArr = yAxis.split('&');
  } else {
    yAxisArr = [yAxis];
  }
  if (!yAxis) {
    return [];
  }
  // 条件项存在多度量
  if (yAxisCondition && yAxisCondition.includes('&')) {
    yAxisConditionArr = yAxisCondition.split('&');
  } else {
    yAxisConditionArr = [yAxisCondition];
  }
  // 如果不存在颜色维度
  if (!legendKey) {
    yAxisArr.forEach((yItem) => {
      const yData = [];
      source.forEach((item) => {
        yData.push(isNullOrEmpty(item[yItem]) ? '' : item[yItem]);
      });
    yData.length && seriesData.push({
        name: yItem,
        fieldName: fieldNameChainMap.yAxis[yItem],
        dataFormatType: 'yAxis',
        data: [{
          value: yData,
          name: yItem
        }],
      })
      // 根据原始字段名称收集数据
      if (fieldNameChainMap?.yAxis[yItem]) {
        conditionData[fieldNameChainMap.yAxis[yItem]].push({
          value: yData,
          name: yItem
        });
      }
    });
    // 雷达图2 数据拐点处理
    if(chartType === 'radarTwo') {
      // 生成系列设置
      seriesData = buildSeries(seriesData);
    }
    // 条件项存在
    if(!$isEmptyArr(yAxisConditionArr)) {
      yAxisConditionArr.forEach((yItem) => {
        const yConditionData = [];
        source.forEach((item) => {
          yConditionData.push(item[yItem]);
        });
        // 根据原始字段名称收集数据
        if(fieldNameChainMap['yAxisCondition'] && fieldNameChainMap['yAxisCondition'][yItem]) {
          conditionData[fieldNameChainMap['yAxisCondition'][yItem]].push({value: yConditionData});
        }
      });
    }
    // 条件格式处理
    const options = {
      conditionData,
      isExistLegend: false, // 是否存在颜色维度
      seriesData,
      legendFieldName: null,
      fieldNameChainMap,
      chartTag: chartType,
    };
    handleConditionExtend(options, conditionOptions);
    return seriesData;
  }
  const legendMap = source.reduce((acc, current) => {
    let name = '';
    xAxisArr.forEach((xItem) => {
      name += `-${current[xItem]}`;
    });
    if (current[legendKey]) {
      if (acc[current[legendKey]]) {
        acc[current[legendKey]].push({
          name: name.substring(1),
          value: current[yAxisArr[0]],
          conditionValue: current[yAxisConditionArr[0]],// 条件项值
          type: current.type || '',
        });
      } else {
        acc[current[legendKey]] = [
          {
            name: name.substring(1),
            value: current[yAxisArr[0]],
            conditionValue: current[yAxisConditionArr[0]],// 条件项值
            type: current.type || '',
          },
        ];
      }
    }
    return acc;
  }, {});
  $each(legendMap, (list, name) => {
    let result = {};
    const data = [];
    const yConditionData = []; // 颜色维度存在时的条件项数据
    xData.forEach((xItem) => {
      // 遍历list数组中每一项的name值与xData数组中的每一项的value值进行查找
      result = list.find((item) => item.name === xItem.value) || { type: list[0].type };
      data.push(isNullOrEmpty(result.value) ? '' : result.value);
      yConditionData.push(result?.conditionValue || 0)
    });
    if (name && data.length) {
       seriesData.push({
        name,
        fieldName: fieldNameChainMap.yAxis[yAxis],
        data: [{
          value: data,
          name,
        }],
      });
      // 根据原始字段名称收集数据
      fieldNameChainMap?.yAxis[yAxis] &&
        conditionData[fieldNameChainMap?.yAxis[yAxis]].push({ value: data });
      fieldNameChainMap?.legend[legendKey] &&
        conditionData[fieldNameChainMap?.legend[legendKey]].push({ value: name });
      // 条件项根据原始字段名收集数据
      if(fieldNameChainMap['yAxisCondition'] && fieldNameChainMap['yAxisCondition'][yAxisCondition]) {
        conditionData[fieldNameChainMap['yAxisCondition'][yAxisCondition]].push({value: yConditionData});
      }
    }
  });
  // 雷达图2 数据拐点处理
  if(chartType === 'radarTwo') {
    // 生成系列设置
    seriesData = buildSeries(seriesData);
  }
  // 条件格式处理
  const optionsObj = {
    conditionData,
    isExistLegend: true, // 是否存在颜色维度
    seriesData,
    legendFieldName: fieldNameChainMap['legend'][legendKey],
    fieldNameChainMap,
    chartTag: chartType,
  };
  handleConditionExtend(optionsObj, conditionOptions);
  return seriesData;
}

/**
 *  格式化雷达图indicator数据
 *  @param {object} datasets
 * */
export function processIndicatorData(datasets, xData, seriesData) {
  const { type, source } = datasets;
  // 如果是静态数据
  if (type === 'STATIC') {
    return radarStaticFormat(source).staticIndicator;
  }
  // 拿到最大值
  const indicatorMax = [];
  $each(seriesData, (resultItem) => {
    const data = resultItem.data[0];
    if (!resultItem || !data.value.length) {
      return;
    }
    $each(data.value, (item) => {
      indicatorMax.push(item);
    });
  });
  const indicatorData = [];
  // 边界处理
  if (!indicatorMax.length) {
    return indicatorData;
  }
  $each(xData, (item) => {
    indicatorData.push({
      name: item.value,
      max: Math.ceil(Math.max(...indicatorMax)),
      values: item.values,
    });
  });
  return indicatorData;
}

/**
 * 雷达图处理静态数据专用函数
 */

function radarStaticFormat(dataList = [], chartType = 'radar') {
  const resultMap = {};
  let result = [];
  // 用于静态数据处理-获取展示维度
  let dataType = [];
  // 数据获取
  let newDataList = [];
  // indicator格式-echarts
  let staticIndicator = [];
  dataType = dataList.filter((item) => item['type']);
  newDataList = dataList.filter((item) => item['name']);
  for (let i = 0, len = newDataList.length; i < len; i++) {
    const name = newDataList[i].name;
    if (!resultMap[name]) {
      resultMap[name] = {
        name,
        value: [],
      };
    }
    resultMap[name].value.push(newDataList[i].value);
  }
  $each(resultMap,(item) => {
    item.value.length && result.push({
      name: item.name,
      data: [item],
      dataFormatType: 'yAxis',
    });
  })
  // 雷达图2 数据拐点处理
  if(chartType === 'radarTwo') {
    // 生成系列设置
    result = buildSeries(result);
  }
  staticIndicator =
    dataType.length > 0 && dataType.map((obj) => ({ name: obj.type, max: obj.max }));
  return { resultMap: result, staticIndicator };
}

/**
 * 基本雷达图
 * @param {object} datasets
 * */
export function basicRadarFormat(datasets) {
  const xAxisData = processXAis(datasets);
  const seriesData = processSeriesData(datasets, {
    xData: xAxisData,
  });
  const indicatorData = processIndicatorData(datasets, xAxisData, seriesData);
  return {
    seriesData,
    xAxisData,
    indicatorData,
  };
}

/**
 * 雷达图2
 * @param {object} datasets
 * */
export function basicRadarTwoFormat(datasets) {
  const xAxisData = processXAis(datasets);
  const seriesData = processSeriesData(datasets, {
    xData: xAxisData,
    chartType: 'radarTwo',
  });
  // 筛选雷达图2数据
  const radarTwoSeriesData = seriesData.filter(item => item.z === 1);
  const indicatorData = processIndicatorData(datasets, xAxisData, radarTwoSeriesData);
  return {
    seriesData,
    xAxisData,
    indicatorData,
  };
}

// 雷达拐点逻辑处理
function buildSeries(result) {
  let seriesData = []
  for (let i in result) {
    const data = result[i].data[0];
    const helper = data.value.map((item, index) => {
      const arr = new Array(data.value.length).fill('');
      arr.splice(index, 1, item);
      return arr;
    })

    const dataItem = [data.value, ...helper].map((item, index) => {
      return {
        type: 'radar',
        symbol: 'circle',
        symbolSize: 5,
        name: result[i].name,
        dataFormatType: 'yAxis',
        lineStyle: {
          width: index === 0 ? 1 : 0
        },
        tooltip: {
          show: index === 0 ? true : false,
        },
        z: index === 0 ? 1 : 2,
        data: [{
          name: data.name,
          value: item,
        }],
        fieldName: result[i].fieldName,
      }
    })
    // 多度量或存在颜色维度
    seriesData = [...seriesData, ...dataItem]
  }
  return seriesData
}
